<template>
    <div class="app-container">
        <el-card class="box-card">
            <div slot="header" class="clearfix">
                <span>家庭作业发布</span>
                <el-button style="float: right; margin-left: 10px;" type="primary" icon="el-icon-s-promotion"
                    @click="submitForm">
                    发 布
                </el-button>
                <el-button style="float: right; " @click="cancel" icon="el-icon-refresh-right">
                    取 消
                </el-button>
            </div>
            <el-form ref="form" :model="form" :rules="rules" label-width="150px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="班级">
                            <el-select v-model="form.classId" filterable clearable style="width:100%"
                                >
                                <el-option v-for="item in teacherClassList" :key="item.id" :value="item.id"
                                    :label="item.className"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="科目" >
                            <el-select v-model="form.subjectId" filterable clearable style="width:100%">
                                <el-option v-for="item in teacherSubjList" :key="item.id" :value="item.id"
                                    :label="item.subjName"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <div style="padding-left: 80px;margin-bottom: 20px;">
                    <template>
                        <el-radio v-model="radio" label="1">文本框</el-radio>
                        <el-radio v-model="radio" label="2">图片</el-radio>
                        <el-radio v-model="radio" label="3">文件（pdf,word,excel）</el-radio>
                    </template>
                </div>
                <div>
                    <el-form-item v-if="this.radio == '1'" label="作业内容" prop="workContent">
                        <el-input type="textarea" :rows="8" placeholder="请输入内容" v-model="form.workContent">
                        </el-input>
                    </el-form-item>
                </div>
                <el-form-item v-if="this.radio == '2'" label="作业内容" prop="workContent">
                    <!-- 图片 -->
                    <el-upload class="avatar-uploader" :headers="upload.header"
                        :action="activeUrl" :show-file-list="false"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="imageUrl" :src="imageUrl" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item v-if="this.radio == '3'" label="作业内容" prop="workContent">
                    <!-- 文件 -->
                    <el-upload drag :headers="upload.header" :action="activeUrl" 
                        :on-success="handleUploadSuccess"
                        :on-error="handleUploadError">
                        <i class="el-icon-upload"></i>
                        <div class="el-upload__text">拖拽文件到此处上传</div>
                    </el-upload>
                </el-form-item>
                <el-form-item label="是否允许评论" prop="isComments">
                    <el-radio label="1" v-model="form.isComments">允许评论</el-radio>
                    <el-radio label="0" v-model="form.isComments">不允许评论</el-radio>
                </el-form-item>
            </el-form>
        </el-card>


    </div>
</template>
  
<script>
import { addOrUpdateWork, workDetails, getTeacherSubj, getTeacherClass } from "@/api/educational/homeWork";
import { getSubjectList, subjectList } from "@/api/educational/subject.js";
import { findTeacherClassPageList } from "@/api/classManage/classInfo";
import { getToken } from '@/utils/auth'

export default {
    name: "termTime",
    data() {
        return {
            upload: {
                url: "",
                header: {
                    "Authorization": 'Bearer ' + getToken()
                }
            },
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            indexs: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 总条数
            total: 0,
            // 科目表格数据
            subjList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 状态数据字典
            statusOptions: [],
            // 日期范围
            dateRange: [],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                name: undefined,
                type: undefined,
                status: undefined
            },
            // 表单参数
            form: {
                classId: null,
                subjectId: null,
                workContent: null,
                isComments: "1"
            },
            // 表单校验
            rules: {
                subjectId: [
                    { required: true, message: "请选择科目", trigger: "blur" }
                ],
                classId: [
                    { required: true, message: "请选择班级", trigger: "blur" }
                ],
                workContent: [
                    { required: this.radio == '1', message: "请填写作业内容", trigger: "blur" }
                ],
                isComments: [
                    { required: true, message: "请选择是否允许评论", trigger: "blur" }
                ],
            },
            subjList: [],
            safeclassList: [],
            id: null,
            teacherSubjList: [],
            teacherClassList: [],
            radio: '1',
            //图片
            imageUrl: '',
            activeUrl: ''
        };
    },
    created() {
        this.id = this.$route.query.id
        if (this.id) {
            workDetails(this.id).then(response => {
                this.form = response.data
            })
        }
        this.getSubjectList()
        this.getClassList()
        this.selectSubject()
        this.getTeacherClassList()
        this.activeUrl = process.env.VUE_APP_BASE_API + "/homeWork/homeWorkFileUpload"
    },
    methods: {
        handleUploadSuccess(res,file){
            this.form.filePath = res.data;
            this.$message.success('文件上传成功');
        },
        handleAvatarSuccess(res, file) {
            this.imageUrl = URL.createObjectURL(file.raw);
            this.form.imgPath = res.data;
            //console.log(res.data);
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        selectSubject() {
            getSubjectList().then(resp => {
                this.teacherSubjList = resp.data

            })
        },
        getTeacherClassList() {
            getTeacherClass().then(resp => {
                this.teacherClassList = resp.data
            })
        },
        cancel() {
            this.$router.push("/educational/homeWork/workHistory")
        },
        //查询班级
        getClassList() {
            this.loading = true;
            findTeacherClassPageList({ pageNum: 1, pageSize: 100 }).then(response => {
                this.safeclassList = response.data.list;

            }
            );
        },
        //查询科目
        getSubjectList() {
            this.loading = true;
            subjectList(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
                this.subjList = response.data.list;
                this.subjList.forEach((item, index) => {

                })
            }
            );
        },
        //获取科目名称
        getSubjectLabel(val) {
            let name = null
            this.subjList.forEach(item => {
                if (item.id == val) {
                    name = item.subjName
                }
            })
            return name
        },
        getClassLabel(val) {
            let name = null
            this.safeclassList.forEach(item => {
                if (item.id == val) {
                    name = item.className
                }
            })
            return name
        },
        /** 提交按钮 */
        submitForm: function () {

            this.$refs["form"].validate(valid => {
                if (valid) {
                    this.form.subjectName = this.getSubjectLabel(this.form.subjectId)
                    this.form.className = this.getClassLabel(this.form.classId)
                    addOrUpdateWork(this.form).then(response => {
                        if (response.code === 200) {
                            this.msgSuccess("发布成功");
                            this.$router.push("/educational/homeWork/workHistory")
                        } else {
                            this.msgError(response.message);
                        }
                    });
                }
            });
        }

    }
};
</script>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
  